#pragma once

#include <iostream>
#include <cstdio>
#include <cstring>
#include <pthread.h>

namespace MutexModule
{
    class Mutex
    {
    public:
        Mutex()
        {
            int n = pthread_mutex_init(&_mutex, nullptr);
            if (n != 0)
            {
                std::cerr << "init mutex fail " << std::strerror(n) << std::endl;
                return;
            }
        }

        void lock()
        {
            int n = pthread_mutex_lock(&_mutex);
            if (n != 0)
            {
                std::cerr << "apply lock failed" << std::strerror(n) << std::endl;
                return;
            }
        }

        void unlock()
        {
            int n = pthread_mutex_unlock(&_mutex);
            if (n != 0)
            {
                std::cerr << "unlock lock failed" << std::strerror(n) << std::endl;
                return;
            }
        }

        pthread_mutex_t *Get() { return &_mutex; }

        ~Mutex()
        {
            int n = pthread_mutex_destroy(&_mutex);
            if (n != 0)
            {
                std::cerr << "destroy mutex fail " << std::strerror(n) << std::endl;
                return;
            }
        }

    private:
        pthread_mutex_t _mutex;
    };

    // RAII风格封装互斥锁
    // 利用对象的声明周期来管理资源
    class mutexguard
    {
    public:
        mutexguard(Mutex &mutex)
            : _m(mutex)
        {
            _m.lock();
        }
        ~mutexguard()
        {
            _m.unlock();
        }

    private:
        Mutex &_m;
    };
}